package com.project.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.DetailBean;
import com.project.bean.FinancialBean;
import com.project.bean.OrderBean;
import com.project.bean.RiderBean;
import com.project.dto.RiderDto;
import com.project.dto.riderToBack.OrderDtoFroBack;
import com.project.dto.riderToUser.InfoDto;
import com.project.dto.riderToUser.OrderDto;
import com.project.mapper.DetailMapper;
import com.project.mapper.FinancialMapper;
import com.project.service.OrderService;
import com.project.service.RiderService;
import com.project.vo.Infos;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lyl
 * @since 2021-10-04
 */
@RestController
@RequestMapping("/rider")
@Api
public class RiderController {
    @Autowired
    RiderService riderService;
    @Autowired
    OrderService orderService;
    @Autowired
    DetailMapper detailMapper;
    @Autowired
    FinancialMapper financialMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;


    /********外部调用模块****************************************************************/

    /**
     * 通过编码调用骑手的权限信息与名字并查看
     *
     * @param code
     * @return
     */
    @ApiOperation(value = "骑手controller", notes = "用于通过code查看骑手对应信息的方法")
    @ApiImplicitParams({@ApiImplicitParam(name = "code", value = "用来code测试")})
    @GetMapping("findRiderByCode/{code}")
    public RiderBean findRiderByCode(@PathVariable String code) {
        return riderService.getRiderByCode(code);
    }


    @PostMapping("backGetMoneyForRider/{riderCode}/{money}")
    public void backGetMoneyForRider(@PathVariable String riderCode, @PathVariable int money) {
        RiderBean riderBean = riderService.getRiderByCode(riderCode);
        //获取骑手的当前余额
        int balance = riderBean.getBalance();
        //进行提现
        riderBean.setBalance(balance - money);
        //更新骑手数据
        riderService.updateById(riderBean);
        //添加骑手提现记录
        FinancialBean financialBean = new FinancialBean();
        //骑手提现时余额
        financialBean.setBalance(balance);
        //骑手提现日期
        financialBean.setDaytime(String.valueOf(LocalDate.now()));
        //骑手提现金额
        financialBean.setGetmoney(money);
        //对应的骑手
        financialBean.setRiderId(riderBean.getRiderId());
        //更新提现单数据库
        financialMapper.insert(financialBean);
    }


    /**
     * 通过编码对骑手的订单进行评分
     *
     * @param code
     * @param userRating
     * @return
     */
    @PostMapping("userRating/{code}/{userRating}")
    public InfoDto userRating(@PathVariable String code, @PathVariable String userRating) {
        OrderBean order = orderService.getOrderByCode(code);
        RiderBean riderBean = riderService.getById(order.getRiderId());
        //用户对订单进行打分
        order.setUserRating(userRating);
        boolean x = orderService.updateById(order);
        //查询出所有的订单
        QueryWrapper<OrderBean> qu = new QueryWrapper<>();
        qu.eq("fk_riderId", riderBean.getRiderId());
        qu.eq("statue", "送货完毕");
        List<OrderBean> list = orderService.list(qu);
        int riderLevel = 0;
        int x1 = 0;
        for (OrderBean orderBean : list) {
            int num = Integer.parseInt(orderBean.getUserRating());
            if (num != 0) {
                x1++;
            }
            riderLevel += num;
        }
        riderLevel = riderLevel / x1;
        riderBean.setLevel(riderLevel);
        boolean flag = riderService.updateById(riderBean);
        if (!flag) {
            return new InfoDto(0, "用户评分失败了");
        }
        return new InfoDto(1, "用户评分成功了");
    }

    /**
     * 进行注册
     *
     * @param riderCode
     * @param name
     * @param tel
     * @param sex
     * @return
     */
    @PostMapping("riderRegister/{riderCode}/{name}/{tel}/{sex}")
    public Infos riderRegister(@PathVariable String riderCode, @PathVariable String name, @PathVariable String tel, @PathVariable String sex) {
        RiderBean riderBean = new RiderBean();
        riderBean.setCode(riderCode);
        riderBean.setName(name);
        riderBean.setTel(tel);
        riderBean.setSex(sex);
        boolean flag = riderService.save(riderBean);
        if (flag) {
            return new Infos(1, "添加人员成功");
        }
        return new Infos(0, "添加人员失败");
    }


    /**
     * 查询所有骑手信息
     *
     * @return
     */
    @GetMapping("findAllRiderInfo")
    public List<RiderDto> findAllRiderInfo() {
        List<RiderBean> list = riderService.findAllRiderInfo();
        List<RiderDto> list2 = new ArrayList<>();
        for (RiderBean riderBean : list) {
            RiderDto riderDto = new RiderDto(riderBean.getCode(), riderBean.getName(), riderBean.getPic(),
                    riderBean.getTel(), riderBean.getSex(), riderBean.getState(), riderBean.getBalance(),
                    riderBean.getRegistrationTime(), riderBean.getLevel(),
                    riderBean.getTodayOrderNum(), riderBean.getTodayIncome(), riderBean.getSumIncome());
            list2.add(riderDto);
        }
        return list2;
    }


    /**
     * 查询骑手订单信息
     *
     * @param code
     * @return
     */
    @GetMapping("getRiderOrderByOrderCode/{code}")
    public OrderBean getRiderOrderByOrderCode(@PathVariable String code) {
        OrderBean orderBean = orderService.getOrderByCode(code);
        return orderBean;
    }


    /**
     * 查询骑手订单信息
     *
     * @param code
     * @return
     */
    @GetMapping("getRiderOrderByCode/{code}")
    public OrderBean getRiderOrderByCode(@PathVariable String code) {
        OrderBean orderBean = orderService.getOrderByCode(code);
        return orderBean;
    }


    /********自身业务接口****************************************************************/

    /**
     * 验证骑手身份
     *
     * @param code
     * @return
     */
    @GetMapping("checkRider/{code}")
    public RiderBean checkRider(@PathVariable String code) {
        return riderService.getRiderByCode(code);
    }


    /**
     * 骑手进行手动刷新订单
     *
     * @param state 当前骑手状态
     * @param area  当前骑手区域
     * @return 接单集合
     */
    @GetMapping("riderRefresh/{state}/{area}")
    public List<OrderBean> riderRefresh(@PathVariable String state, @PathVariable String area) {
        if (state.equals("休息中")) {
            return new ArrayList<>();
        }
        //此处进行方法调用
        return orderService.findAllOrder(state, area);
    }

    /**
     * 骑手进行抢单
     *
     * @param riderCode
     * @param orderCode
     * @return
     */
    @PostMapping("riderGrabOrder/{riderCode}/{orderCode}")
    public Infos riderGrabOrder(@PathVariable String riderCode, @PathVariable String orderCode) {
        //此处进行抢单方法调用
        OrderBean orderBean = orderService.getOrderByCode(orderCode);
        RiderBean riderBean = riderService.getRiderByCode(riderCode);
        OrderDto orderDto = new OrderDto();
        orderDto.setOrderCode(orderCode);
        orderDto.setRiderCode(riderCode);
        orderDto.setStatue(orderBean.getStatue());
        orderDto.setRiderName(riderBean.getName());
        CorrelationData correlationData = new CorrelationData("");
        rabbitTemplate.convertAndSend("riderDirectExchange", "Rider.Queue", orderDto, correlationData);
        return orderService.updateOrderState(riderCode, orderCode, "unchecked");
    }

    /**
     * 更新骑手接单数量
     *
     * @param num
     * @param riderCode
     * @return
     */
    @PostMapping("updateRiderNum/{riderCode}/{num}")
    public Infos updateRiderNum(@PathVariable int num, @PathVariable String riderCode) {
        RiderBean riderBean = riderService.getRiderByCode(riderCode);
        riderBean.setOrderNum(num);
        boolean flag = riderService.updateById(riderBean);
        if (flag) {
            return new Infos(1, "更新接单数成功");
        }
        return new Infos(0, "更新接单数量失败");
    }

    /**
     * 骑手进行查询需取货订单集合
     *
     * @param riderCode
     * @return
     */
    @GetMapping("riderCheckOrder/{riderCode}")
    public List<OrderBean> riderCheckOrder(@PathVariable String riderCode) {
        //此处进行方法的调用
        return orderService.findAllOrderByStatue(riderCode, "已接单");
    }

    /**
     * 骑手确认取货完毕
     *
     * @param riderCode 骑手编号
     * @param orderCode 订单编号
     * @return
     */
    @PostMapping("riderConfirmPickup/{riderCode}/{orderCode}")
    public Infos riderConfirmPickup(@PathVariable String riderCode, @PathVariable String orderCode) {
        //此处进行方法的调用
        return orderService.updateOrderState(riderCode, orderCode, "sending");
    }


    /**
     * 骑手进行查询需送货订单集合
     *
     * @param riderCode
     * @return
     */
    @GetMapping("riderCheckDelivery/{riderCode}")
    public List<OrderBean> riderCheckDelivery(@PathVariable String riderCode) {
        return orderService.findAllOrderByStatue(riderCode, "送货中");
    }

    /**
     * 骑手确认送货完毕，同时对用户发送请求信息，进行评分。还有同时向后台发送消息
     *
     * @param riderCode 骑手编号
     * @param orderCode 订单编号
     * @return
     */
    @PostMapping("riderPickUp/{riderCode}/{orderCode}")
    public OrderBean riderPickUp(@PathVariable String riderCode, @PathVariable String orderCode) {
        //此处进行方法的调用
        Infos in = orderService.updateOrderState(riderCode, orderCode, "ending");
        System.out.println(in);
        //此处需要传回一个详情的订单信息
        OrderBean orderBean = orderService.getOrderByCode(orderCode);
        QueryWrapper<DetailBean> qu = new QueryWrapper<>();
        qu.eq("fk_orderId", orderBean.getCode());
        List<DetailBean> list = detailMapper.selectList(qu);
        orderBean.setList(list);
        InfoDto infoDto = new InfoDto();

        infoDto.setCode(1);
        infoDto.setDetail("订单已配送成功，请进行评分");
        infoDto.setOrderCode(orderCode);
        infoDto.setEndtime(orderBean.getEndTime());
        CorrelationData correlationData = new CorrelationData("");
        rabbitTemplate.convertAndSend("riderDirectExchange", "Rider.Queue2", infoDto, correlationData);
        OrderDtoFroBack o = new OrderDtoFroBack();
        BeanUtils.copyProperties(orderBean, o);

        rabbitTemplate.convertAndSend("riderDirectExchange", "Rider.Queue3", o, correlationData);

        return orderBean;
    }

    /**
     * 查看今日完成单数、今日收入
     *
     * @param riderCode 骑手编号
     * @param daytime   当前日期
     * @return
     */
    @GetMapping("checkRiderInformation/{riderCode}/{daytime}")
    public RiderBean checkRiderInformation(@PathVariable String riderCode, @PathVariable String daytime) {
        //此处调用方法
        //用户、今日完成单数、今日收入、头像
        return riderService.findRiderByCodeAndDate(riderCode, daytime);
    }


    /**
     * 查询骑手
     *
     * @param riderCode 骑手编号
     * @param daytime   今日日期
     * @return
     */
    @GetMapping("checkTodayOrderDetail/{riderCode}/{daytime}")
    public List<OrderBean> checkTodayOrderDetail(@PathVariable String riderCode, @PathVariable String daytime) {
        //此处调用方法
        return orderService.findAllOrderByRiderCodeAndDateAndStatue(riderCode, daytime);
        //订单集合：订单编号、送达时间、起始地址、骑手此单佣金、实际送达时间
    }


    /**
     * 骑手对自身账户进行查看，可查看总收入、当日总收入
     *
     * @param riderCode 骑手编号
     * @param starttime 今日起始时间
     * @param endtime   今日结束时间
     * @return
     */
    @GetMapping("checkRiderAccount/{riderCode}/{starttime}/{endtime}")
    public RiderBean checkRiderAccount(@PathVariable String riderCode, @PathVariable String starttime, @PathVariable String endtime) {
        //此处调用方法
        //查询出的总收入以及骑手当日收入
        return riderService.findRiderByIncome(riderCode, starttime, endtime);
    }

    /**
     * 骑手对自己的历史订单进行查询
     *
     * @param riderCode
     * @returnr
     */
    @GetMapping("checkRiderHistoricalOrder/{riderCode}")
    public List<OrderBean> checkRiderHistoricalOrder(@PathVariable String riderCode) {
        //此处调用方法
        //查询出的
        return orderService.findOrderByRiderCodeAndStatus(riderCode);
    }

    @GetMapping("findRiderStatus/{riderCode}")
    public RiderBean findRiderStatus(@PathVariable String riderCode) {
        return riderService.getRiderByCode(riderCode);
    }

    @PostMapping("updateRiderStatus/{riderCode}/{status}")
    public Infos updateRiderStatus(@PathVariable String riderCode, @PathVariable String status) {
        return riderService.setRiderState(riderCode, status);
    }

    /**
     * 根据骑手编号和新电话号码修改电话
     *
     * @param riderCode 骑手编号
     * @param phone     新电话号码
     * @return 是否成功
     */
    @PostMapping("updatePhone/{riderCode}/{phone}")
    public Infos updatePhone(@PathVariable String riderCode, @PathVariable String phone) {
        Infos infos = riderService.updatePhone(riderCode, phone);
        if (infos.getDetail().equals("修改成功")) {
            RiderBean riderBean = riderService.getRiderByCode(riderCode);
            RiderDto dto = new RiderDto();
            BeanUtils.copyProperties(riderBean, dto);

            CorrelationData correlationData = new CorrelationData("");
            rabbitTemplate.convertAndSend("riderDirectExchange", "Rider.Queue6", dto, correlationData);
        }

        return infos;
    }

    @PostMapping("riderGetMoney/{riderCode}/{money}")
    public Infos riderGetMoney(@PathVariable String riderCode, @PathVariable int money) {
        RiderBean riderBean = riderService.getRiderByCode(riderCode);
        //获取骑手的当前余额
        int balance = riderBean.getBalance();
        //如果余额小于提现金额则不予提现
        if (balance < money) {
            return new Infos(0, "提现申请失败，请输入正确的金额");
        }
        RiderDto riderDto = new RiderDto();
        //骑手编号
        riderDto.setCode(riderCode);
        //骑手希望提现的金额
        riderDto.setRiderGetMoney(money);
        CorrelationData c = new CorrelationData("");
        rabbitTemplate.convertAndSend("riderDirectExchange", "Rider.Queue5", riderDto, c);
        return new Infos(1, "提现申请已提交，请耐心等待");
    }

    @GetMapping("findProduct/{orderCode}")
    public OrderBean findProduct(@PathVariable String orderCode) {
        //此处需要传回一个详情的订单信息
        OrderBean orderBean = orderService.getOrderByCode(orderCode);
        QueryWrapper<DetailBean> qu = new QueryWrapper<>();
        qu.eq("fk_orderId", orderBean.getCode());
        List<DetailBean> list = detailMapper.selectList(qu);
        orderBean.setList(list);
        return orderBean;
    }

    /**
     * 查询当前提现记录
     *
     * @param riderCode
     * @return
     */
    @GetMapping("getFinancialInfo/{riderCode}")
    public List<FinancialBean> getFinancialInfo(@PathVariable String riderCode) {
        RiderBean r = riderService.getRiderByCode(riderCode);
        QueryWrapper<FinancialBean> qu = new QueryWrapper<>();
        qu.eq("fk_riderId", r.getRiderId());
        return financialMapper.selectList(qu);
    }

}
